#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"

using namespace LogModule;
const static int gsockfd = -1;
const static uint16_t gdefaultport = 8080;
class UdpServer
{
public:
    UdpServer(uint16_t port = gdefaultport) : _sockfd(gsockfd), _addr(port), _isrunning(false)
    {
    }
    void InitServer()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: " << strerror(errno);
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd is " << _sockfd;
        
        int n = bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }
    void Start()
    {
        _isrunning = true;
        while (true)
        {
            char inbuffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, CONV(&peer), &len);
            if (n > 0)
            {
                InetAddr cli(peer);
                inbuffer[n] = 0;
                std::string clientinfo = cli.Ip() + ":" + std::to_string(cli.Port()) + "# " + inbuffer;
                std::string echo_string = "echo#";
                echo_string += clientinfo;
                sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, CONV(&peer), sizeof(peer));
            }
        }
        _isrunning = false;
    }
    ~UdpServer()
    {
        if(_sockfd>gsockfd)
            ::close(_sockfd);
    }
private:
    int _sockfd;
    InetAddr _addr; // ip+port
    bool _isrunning;
};